package com.heima.article.service.impl;

import com.heima.article.service.ArticleInfoService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ArticleInfoServiceImpl implements ArticleInfoService {

    @Autowired
    private CacheService cacheService;

    /**
     * 文章详情-行为数据回显
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        // 1. 检查数据
        if(dto == null || dto.getArticleId() == null || dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 回显数据
        Map<String, Boolean> map = new HashMap<>();
        Boolean islike = false, isunlike = false, iscollection = false, isfollow = false;
        // 3.1 是否点赞
        String likeJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if(likeJson != null){
            islike = true;
        }
        // 3.2 是否不喜欢
        String unLikeJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if(unLikeJson != null){
            isunlike = true;
        }
        // 3.3 是否收藏
        String collectiontJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getArticleId().toString());
        if(collectiontJson != null){
            iscollection = true;
        }
        // 3.4 是否关注
        Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
        if(score != null){
            isfollow = true;
        }
        map.put("islike", islike);
        map.put("isunlike", isunlike);
        map.put("iscollection", iscollection);
        map.put("isfollow", isfollow);
        return ResponseResult.okResult(map);
    }
}
